<template>
  <div class="login">
    <div class="login-box">
      <div class="title">火星</div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="userName">
          <el-input
            prefix-icon="el-icon-user"
            v-model="ruleForm.userName"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="userPwd">
          <el-input
            prefix-icon="el-icon-lock"
            show-password
            v-model="ruleForm.userPwd"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            @click="loginClick('ruleForm')"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        userName: "",
        userPwd: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        userPwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  mounted() {},
  methods: {
    loginClick(formName) {
      this.$refs[formName].validate( async (valid) => {
        if (valid) {
            let res = await this.userApi.doLogin(this.ruleForm);
            this.$store.commit('saveUserInfo', res);
            this.$store.commit('saveToken', res.token);
            this.$message.success({
              message: '登录成功',
              offset: 100,
            });
            this.$router.push('/layout');
        } else {
            this.$message.error('用户名和密码不能为空,请重新输入');
            return false;
        }
      });
    },
  },
};
</script>

<style scoped lang='scss'>
.login {
  width: 100vw;
  height: 100vh;
  background-color: #f9fcff;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-box {
    width: 500px;
    padding: 50px;
    border-radius: 5px;
    box-shadow: 0 0 10px 5px #e1e3e5;
    .title {
      font-size: 50px;
      text-align: center;
      margin-bottom: 30px;
    }
  }
}
</style>
